package com.ahuan.controller;

import com.ahuan.domain.Dept;
import com.ahuan.exception.BusinessException;
import com.ahuan.resp.Res;
import com.ahuan.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/Dept")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @PostMapping("/save")
    public Res saveDept(Dept dept) {
        try {
            dept.setEditUser(MDC.get("userId"));
            log.info("dept:{}", dept);
            if (dept.getDeptId() == null || dept.getDeptId() == "") {
                if (deptService.addDept(dept)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            } else {

                if (deptService.editDept(dept)) {
                    return Res.successOperate();
                } else {
                    return Res.failOperate();
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new BusinessException("部门信息保存失败");
        }
//        return Res.successOperate();
    }

    @PostMapping("/list")
    public Res getDeptList(Integer page, Integer limit) {
        try {
            log.info("page:{},limit:{}", page, limit);
            List<Dept> list = deptService.queryDeptList(page, limit);
            log.info("list:{}", list);
            if (list.size() > 0) {
                return Res.successOperate(list, list.size());
            }
            return Res.failOperate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("部门列表查询失败");
        }
    }

    @GetMapping("/delete")
    public Res deleteDept(@RequestParam("ids") String deptId){
        try {
            log.info("ResetPwd DeptId:{}", deptId);
            if(deptService.delete(deptId)){
                return Res.successOperate();
            }
            return  Res.failOperate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("部门删除失败");
        }
    }
}
